<?php

namespace common\lib;

use Yii;
use yii\data\ActiveDataProvider;
use yii\helpers\BaseJson;

class Helper {
    /*
     * 格式化返回的数据
     */

    public static function format_data($code, $data) {
        $msg = Yii::$app->params['a' . $code];
        return ['code' => $code, 'msg' => $msg, 'data' => $data];
    }

    /*
     * 根据ActiveDataProvider返回的数据
     */

    public static function format_list_bydp($code, ActiveDataProvider $data_provider) {
        $msg = Yii::$app->params['a' . $code];
        $data = ['items' => $data_provider->getModels(), 'totalCount' => $data_provider->getTotalCount()];
        return ['code' => $code, 'msg' => $msg, 'data' => $data];
    }

    public static function format_error($error_code, $msg) {
        return ['code' => $error_code, 'msg' => $msg];
    }

    public static function xd_api_json($error_code, $data = '') {
        $res = \Yii::$app->params[$error_code];
        if (!$res) {
            $res = \Yii::$app->params[$ERROR_DEFAULT];
        }
        if (empty($data)) {
            $data = array();
        } else {
            $res['data'] = $data;
        }
        $res['st'] = time();
        return BaseJson::encode($res);
    }

    public static function trips($str) {
        $str = trim($str);
        $str = strip_tags($str, "");
        $str = preg_replace("{\t}", "", $str);
        $str = preg_replace("{\r\n}", "", $str);
        $str = preg_replace("{\r}", "", $str);
        $str = preg_replace("{\n}", "", $str);
        $str = preg_replace("{ }", "", $str);
        $str = str_replace(' ', '', $str);
        return $str;
    }

    /**
     * curl post
     * @param str $url
     * @param array $data
     * @param array $options
     * @return boolean
     */
    public static function curl_post($url, $data = NULL, array $options = array()) {
        if (!$url) {
            return false;
        }
        if (!$data) {
            return false;
        }
        $headers = array("Content-type: application/json;charset='utf-8'", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 40);
        curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($data) ? http_build_query($data) : $data); // 如果为数组，调用http_build_query
        $output = json_decode(curl_exec($ch), true);
        if (curl_errno($ch)) { // 出错则显示错误信息
            return false;
        }
        curl_close($ch);
        return $output;
    }

    /**
     * curl get
     * @param str $url
     * @return boolean
     */
    public static function curl_get($url) {
        if (!$url) {
            return false;
        }
        $ch = curl_init();
        // 2. 设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        // 3. 执行并获取HTML文档内容
        $output = json_decode(curl_exec($ch), true);
        // 4. 释放curl句柄
        curl_close($ch);
        return $output;
    }

    /**
     * 检查是否为手机号码
     * @return boolean
     */
    public static function xd_is_mobilephone($mobilephone) {
        if (preg_match("/^((\(\d{2,3}\))|(\d{3}\-))?1[3,4,5,7,8]\d{9}$/", $mobilephone)) {
            return true;
        }
        return false;
    }

    /**
     * 检查六位验证码
     * @return boolean
     */
    function xd_is_four_code($code) {
        if (preg_match("/^[0-9]{4}$/", $code)) {
            return true;
        }

        return false;
    }

    /**
     *  生成指定长度的随机字符串(包含大写英文字母, 小写英文字母, 数字)
     * 
     * @author Wu Junwei <www.wujunwei.net>
     * 
     * @param int $length 需要生成的字符串的长度
     * @return string 包含 大小写英文字母 和 数字 的随机字符串
     */
    public static function random_str($length) {
        //生成一个包含 大写英文字母, 小写英文字母, 数字 的数组
        $arr = array_merge(range(0, 9), range('a', 'z'), range('A', 'Z'));
        $str = '';
        $arr_len = count($arr);
        for ($i = 0; $i < $length; $i++) {
            $rand = mt_rand(0, $arr_len - 1);
            $str.=$arr[$rand];
        }
        return $str;
    }

    public static function characet($data) {
        if (!empty($data)) {
            $fileType = mb_detect_encoding($data, array('UTF-8', 'GBK', 'LATIN1', 'BIG5'));
            if ($fileType != 'UTF-8') {
                $data = mb_convert_encoding($data, 'utf-8', $fileType);
            }
        }
        return $data;
    }

    /**
     * 验证手机号是否正确

     */
    function isMobile($mobile) {
        if (!is_numeric($mobile)) {
            return false;
        }
        return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $mobile) ? true : false;
    }

    /**
     * 浏览器友好的变量输出
     * @param mixed $var 变量
     * @param boolean $echo 是否输出 默认为True 如果为false 则返回输出字符串
     * @param string $label 标签 默认为空
     * @param boolean $strict 是否严谨 默认为true
     * return void|string
     */
    public static function dump($var, $echo = true, $label = null, $strict = true) {
        $label = ($label === null) ? '' : rtrim($label) . ' ';
        if (!$strict) {
            if (ini_get('html_errors')) {
                $output = print_r($var, true);
                $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
            } else {
                $output = $label . print_r($var, true);
            }
        } else {
            ob_start();
            var_dump($var);
            $output = ob_get_clean();
            if (!extension_loaded('xdebug')) {
                $output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', $output);
                $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
            }
        }
        if ($echo) {
            echo($output);
            return null;
        } else
            return $output;
    }

}
